﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;
using Chisholm.Windows.Live.SSOClient;
using Chisholm.Windows.Live.Library;
using System.ComponentModel;
using System.Web.UI.HtmlControls;
using System.Security.Principal;
using Chisholm.Windows.Live.Security;
using Microsoft.SharePoint;
using System.Web;
using System.Configuration;

namespace Chisholm.Windows.Live.WebParts
{
    /// <summary>
    /// This web part can be placed inside of SharePoint (or an ASP.NET page) and will provide a 
    /// logo and access buttons for Live@EDU via single sign on, using either a direct access method
    /// or via the middle tier SSO server
    /// </summary>
    [ToolboxData("<{0}:LiveEDUPart runat=server></{0}:LiveEDUPart>")]
    public class LiveEDUPart : WebPart
    {
        #region Middle Tier SSO Server Settings

        private string _ssoserver;
        /// <summary>
        /// If using the middle tier SSO Server for Windows Live Authentication, this is the name of the server
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU SSO Server"), Description(@"If using the middle tier SSO Server for Windows Live Authentication, this is the name of the server.")]
        public string SSOServer 
        {
            get { return _ssoserver; }
            set { _ssoserver = value; }
        }

        private int _ssoserverport;
        /// <summary>
        /// If using the middle tier SSO Server for Windows Live Authentication, this is the port number the SSO Service is running on
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU SSO Server"), Description(@"If using the middle tier SSO Server for Windows Live Authentication, this is the port number the SSO Service is running on.")]
        public int SSOServerPort
        {
            get { return _ssoserverport; }
            set { _ssoserverport = value; }
        }

        private string _ssoserveruser;
        /// <summary>
        /// If using the middle tier SSO Server for Windows Live Authentication, this is the full domain and username to use to access
        /// the middle tier Single Sign On Server
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU SSO Server"), Description(@"If using the middle tier SSO Server for Windows Live Authentication, this is the full domain and username to use to access
            the middle tier Single Sign On Server.")]
        public string SSOServerUser
        {
            get { return _ssoserveruser; }
            set { _ssoserveruser = value; }
        }

        private string _ssoserveruserpassword;
        /// <summary>
        /// If using the middle tier SSO Server for Windows Live Authentication, this is the password relating to the user used to access
        /// the middle tier Single Sign On Server
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU SSO Server"), Description(@"If using the middle tier SSO Server for Windows Live Authentication, this is the password relating to the user used to access
            the middle tier Single Sign On Server.")]
        public string SSOServerPassword
        {
            get { return _ssoserveruserpassword; }
            set { _ssoserveruserpassword = value; }
        }

        #endregion

        #region Direct Microsoft Credential Server Settings

        private int _siteid;
        /// <summary>
        /// If connecting directly to the Microsoft Credential Service, this is the Site ID supplied by Live@EDU's Ed-Desk
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Direct Connection"), Description(@"If connecting directly to the Microsoft Credential Service, this is the Site ID supplied by Live@EDU's Ed-Desk.")]
        public int SiteID
        {
            get { return _siteid; }
            set { _siteid = value; }
        }

        private string _proxyserver;
        /// <summary>
        /// If connecting directly to the Microsoft Credential Service, this is the proxy server (if required) used to connect to the internet
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Direct Connection"), Description(@"If connecting directly to the Microsoft Credential Service, this is the proxy server (if required) used to connect to the internet.")]
        public string ProxyServer
        {
            get { return _proxyserver; }
            set { _proxyserver = value; }
        }

        private int _logintimeout;
        /// <summary>
        /// If connecting directly to the Microsoft Credential Service, this is time (in seconds) that issued Short Lived Tokens are valid for
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Direct Connection"), Description(@"If connecting directly to the Microsoft Credential Service, this is time (in seconds) that issued Short Lived Tokens are valid for.")]
        public int LoginTimeout
        {
            get { return _logintimeout; }
            set { _logintimeout = value; }
        }

        private string _certificatefile;
        /// <summary>
        /// If connecting directly to the Microsoft Credential Service, and you have the Live@EDU Ed-Desk issued SSL certificate stored on the web server's
        /// hard disk, this is the full path and name of the Private Key Exchange (PFX) file
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Direct Connection"), Description(@"If connecting directly to the Microsoft Credential Service, and you have the Live@EDU Ed-Desk issued SSL certificate stored on the web server's
            hard disk, this is the full path and name of the Private Key Exchange (PFX) file.")]
        public string CertificateFile
        {
            get { return _certificatefile; }
            set { _certificatefile = value; }
        }

        private string _certificatepassword;
        /// <summary>
        /// If connecting directly to the Microsoft Credential Service, and you have the Live@EDU Ed-Desk issued SSL certificate stored on the web server's
        /// hard disk, this is the password to access the certificate
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Direct Connection"), Description(@"If connecting directly to the Microsoft Credential Service, and you have the Live@EDU Ed-Desk issued SSL certificate stored on the web server's
            hard disk, this is the password to access the certificate.")]
        public string CertificatePassword
        {
            get { return _certificatepassword; }
            set { _certificatepassword = value; }
        }

        private string _certificatethumbprint;
        /// <summary>
        /// If connecting directly to the Microsoft Credential Service, and you have the Live@EDU Ed-Desk issued SSL certificate stored in the Personal 
        /// Store of the Local Computer's Certificate collection, this is the Thumb Print of the certificate
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Direct Connection"), Description(@"If connecting directly to the Microsoft Credential Service, and you have the Live@EDU Ed-Desk issued SSL certificate stored in the Personal 
            Store of the Local Computer's Certificate collection, this is the Thumb Print of the certificate.")]
        public string CertificateThumbprint
        {
            get { return _certificatethumbprint; }
            set { _certificatethumbprint = value; }
        }

        #endregion

        #region Security Settings

        private AccountStoreTypes _accountstore;
        /// <summary>
        /// If connecting directly to the Microsoft Credential Service, this is the details of how to look up the users e-mail
        /// address to pass through to the service
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Security"), Description(@"If connecting directly to the Microsoft Credential Service, this is the details of how to look up the users e-mail
            address to pass through to the service.")]
        public AccountStoreTypes AccountStore
        {
            get { return _accountstore; }
            set { _accountstore = value; }
        }

        private string _activedirectorydomain;
        /// <summary>
        /// If connecting directly to the Microsoft Credential Service, and using Active Directory to look up the users
        /// e-mail address, this is the name of the domain the users are authenticated against
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Security"), Description(@"If connecting directly to the Microsoft Credential Service, and using Active Directory to look up the users
        e-mail address, this is the name of the domain the users are authenticated against.")]
        public string ActiveDirectoryDomain
        {
            get { return _activedirectorydomain; }
            set { _activedirectorydomain = value; }
        }

        private string _activedirectoryproperty;
        /// <summary>
        /// If connecting directly to the Microsoft Credential Service, and using Active Directory to look up the users
        /// e-mail address, this is the name of the property in Active Directory containing the e-mail address
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Security"), Description(@"If connecting directly to the Microsoft Credential Service, and using Active Directory to look up the users
         e-mail address, this is the name of the property in Active Directory containing the e-mail address.")]
        public string ActiveDirectoryProperty
        {
            get { return _activedirectoryproperty; }
            set { _activedirectoryproperty = value; }
        }

        private string _activedirectoryuser;
        /// <summary>
        /// If connecting directly to the Microsoft Credential Service, and using Active Directory to look up the users
        /// e-mail address, this is the user with enough permissions to look up Active Directory
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Security"), Description(@"If connecting directly to the Microsoft Credential Service, and using Active Directory to look up the users
        e-mail address, this is the user with enough permissions to look up Active Directory.")]
        public string ActiveDirectoryUser
        {
            get { return _activedirectoryuser; }
            set { _activedirectoryuser = value; }
        }

        private string _activedirectorypassword;
        /// <summary>
        /// If connecting directly to the Microsoft Credential Service, and using Active Directory to look up the users
        /// e-mail address, this is the password of the user with enough permissions to look up Active Directory
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Security"), Description(@"If connecting directly to the Microsoft Credential Service, and using Active Directory to look up the users
        e-mail address, this is the password of the user with enough permissions to look up Active Directory.")]
        public string ActiveDirectoryPassword
        {
            get { return _activedirectorypassword; }
            set { _activedirectorypassword = value; }
        }

        #endregion

        #region General Settings

        private SSOAuthenticationMethods _accesstype;
        /// <summary>
        /// The method used for authenticating against Windows Live for SSO, which can either be direct
        /// to the Microsoft Credential Server or via the middle tier SSO Server
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Single Sign On (SSO)"), Description(@"The method used for authenticating against Windows Live for SSO, which can either be direct
            to the Microsoft Credential Server or via the middle tier SSO Server")]
        public SSOAuthenticationMethods AccessType
        {
            get { return _accesstype; }
            set { _accesstype = value; }
        }

        private string _liveedudomain;
        /// <summary>
        /// This is the domain suffix for Live@EDU e-mails (e.g. mail.institute.edu.au)
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Appearance"), Description(@"This is the domain suffix for Live@EDU e-mails (e.g. mail.institute.edu.au).")]
        public string LiveEDUDomain
        {
            get { return _liveedudomain; }
            set { _liveedudomain = value; }
        }

        private string _liveeduimageurl;
        /// <summary>
        /// This is the URL to the image to display as the main Live@EDU Login button
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Appearance"), Description(@"This is the URL to the image to display as the main Live@EDU Login button.")]
        public string LiveEDUImageURL
        {
            get { return _liveeduimageurl; }
            set { _liveeduimageurl = value; }
        }

        private bool _displaymaillogin;
        /// <summary>
        /// Whether to display the login button for direct E-mail access
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Appearance"), Description(@"Whether to display the login button for direct E-mail access.")]
        public bool DisplayMailLogin
        {
            get { return _displaymaillogin; }
            set { _displaymaillogin = value; }
        }

        private string _mailimageurl;
        /// <summary>
        /// This is the URL to the image to display as the Mail login button
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Appearance"), Description(@"This is the URL to the image to display as the Mail login button.")]
        public string MailImageURL
        {
            get { return _mailimageurl; }
            set { _mailimageurl = value; }
        }

        private bool _displayskydrivelogin;
        /// <summary>
        /// Whether to display the login button for direct SkyDrive access
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Appearance"), Description(@"Whether to display the login button for direct SkyDrive access.")]
        public bool DisplaySkyDriveLogin
        {
            get { return _displayskydrivelogin; }
            set { _displayskydrivelogin = value; }
        }

        private string _skydriveimageurl;
        /// <summary>
        /// This is the URL to the image to display as the SkyDrive login button
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Appearance"), Description(@"This is the URL to the image to display as the SkyDrive login button.")]
        public string SkyDriveImageURL
        {
            get { return _skydriveimageurl; }
            set { _skydriveimageurl = value; }
        }

        private bool _displaycalendarlogin;
        /// <summary>
        /// Whether to display the login button for direct Calendar access
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Appearance"), Description(@"Whether to display the login button for direct Calendar access.")]
        public bool DisplayCalendarLogin
        {
            get { return _displaycalendarlogin; }
            set { _displaycalendarlogin = value; }
        }

        private string _calendarimageurl;
        /// <summary>
        /// This is the URL to the image to display as the Calendar login button
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Appearance"), Description(@"This is the URL to the image to display as the Calendar login button.")]
        public string CalendarImageURL
        {
            get { return _calendarimageurl; }
            set { _calendarimageurl = value; }
        }

        private bool _displayphotologin;
        /// <summary>
        /// Whether to display the login button for direct Photo access
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Appearance"), Description(@"Whether to display the login button for direct Photo access.")]
        public bool DisplayPhotoLogin
        {
            get { return _displayphotologin; }
            set { _displayphotologin = value; }
        }

        private string _photoimageurl;
        /// <summary>
        /// This is the URL to the image to display as the Photo login button
        /// </summary>
        [WebBrowsable(true), Personalizable(true)]
        [Category("Windows Live@EDU Appearance"), Description(@"This is the URL to the image to display as the Photo login button.")]
        public string PhotoImageURL
        {
            get { return _photoimageurl; }
            set { _photoimageurl = value; }
        } 

        #endregion        

        #region Events

        /// <summary>
        /// This loads the Live@EDU web part onto the default content panel for this control
        /// </summary>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                // Before starting to initialise, check whether any settings have been specified 
                // globally in the web.config to avoid having to assign them in SharePoint directly
                LoadGlobalSettings();

                // First we need to determine whether we are connecting directly to the Microsoft Credential
                // Service or through the middle tier SSO Server, and grab an SSO Client to use based on
                // that setup
                SSOClient.SSOClient client = GetClient();

                // Now we need to determine where to locate the e-mail property for the user (their windows
                // live ID) and pass that through
                string windowsliveid = GetLiveAccount();

                // Then we need to grab the e-mail redirection details
                string emailredirect = client.GetRedirectionURL(windowsliveid, LiveServiceTypes.Mail);
                string skydriveredirect = client.GetRedirectionURL(windowsliveid, LiveServiceTypes.SkyDrive);
                string calendarredirect = client.GetRedirectionURL(windowsliveid, LiveServiceTypes.Calendar);
                string photoredirect = client.GetRedirectionURL(windowsliveid, LiveServiceTypes.Photos);

                // If the redirects are still empty, set them to the main login pages
                if (emailredirect == String.Empty)
                    emailredirect = "http://mail.live.com";
                if (skydriveredirect == String.Empty)
                    skydriveredirect = "http://skydrive.live.com";
                if (calendarredirect == String.Empty)
                    calendarredirect = "http://calendar.live.com";
                if (photoredirect == String.Empty)
                    photoredirect = "http://photos.live.com";

                // Prepare our controls for the layout (using a table) and buttons for options
                HtmlTable livelogon = new HtmlTable();
                HtmlTableRow mainbuttonrow = new HtmlTableRow();
                HtmlTableCell mainbuttoncell = new HtmlTableCell();
                HtmlTableRow subbuttonrow = new HtmlTableRow();
                HtmlTableCell mailbuttoncell = new HtmlTableCell();
                HtmlTableCell skydrivebuttoncell = new HtmlTableCell();
                HtmlTableCell calendarbuttoncell = new HtmlTableCell();
                HtmlTableCell photobuttoncell = new HtmlTableCell();
                HtmlTableRow liveidrow = new HtmlTableRow();
                HtmlTableCell liveidcell = new HtmlTableCell();
                Image mainloginimage = new Image();
                Image mailloginimage = new Image();
                Image skydriveloginimage = new Image();
                Image calendarloginimage = new Image();
                Image photologinimage = new Image();
                Label liveid = new Label();

                // Set the layout properties of our controls
                livelogon.Width = "95%";
                livelogon.Align = "Center";
                livelogon.Attributes.Add("style", "text-align: center");
                mainbuttoncell.Width = "100%";
                mainbuttoncell.ColSpan = 4;
                mainbuttoncell.Align = "Center";
                mainbuttoncell.VAlign = "Center";
                mailbuttoncell.Width = "25%";
                mailbuttoncell.Align = "Center";
                mailbuttoncell.VAlign = "Center";
                mailbuttoncell.Attributes.Add("style", "text-align: center");
                skydrivebuttoncell.Width = "25%";
                skydrivebuttoncell.Align = "Center";
                skydrivebuttoncell.VAlign = "Center";
                skydrivebuttoncell.Attributes.Add("style", "text-align: center");
                calendarbuttoncell.Width = "25%";
                calendarbuttoncell.Align = "Center";
                calendarbuttoncell.VAlign = "Center";
                calendarbuttoncell.Attributes.Add("style", "text-align: center");
                photobuttoncell.Width = "25%";
                photobuttoncell.Align = "Center";
                photobuttoncell.VAlign = "Center";
                photobuttoncell.Attributes.Add("style", "text-align: center");
                liveidcell.Width = "100%";
                liveidcell.ColSpan = 4;
                liveidcell.Align = "Center";
                liveidcell.VAlign = "Center";
                liveidcell.Attributes.Add("style", "text-align: center");

                // Set the display properties of our controls
                mainloginimage.ImageUrl = _liveeduimageurl;
                mailloginimage.ImageUrl = _mailimageurl;
                skydriveloginimage.ImageUrl = _skydriveimageurl;
                calendarloginimage.ImageUrl = _calendarimageurl;
                photologinimage.ImageUrl = _photoimageurl;

                // Update our Live@EDU login details
                string[] userliveid = windowsliveid.Split('@');
                if (userliveid.Length == 2)
                {
                    liveid.Text = "<b>" + userliveid[0] + "</b>@<br>" + userliveid[1];
                }
                else
                {
                    liveid.Text = userliveid[0];
                }

                // Finally set our action properties
                mainloginimage.Attributes.Add("onclick", "javascript:window.open('" +
                    emailredirect + "');");
                mainloginimage.ToolTip = "Click here to open Windows Live";
                mainloginimage.Attributes.Add("onmouseover", "this.style.cursor='hand';");
                mainloginimage.Attributes.Add("onmouseout", "this.style.cursor='default';");
                mailloginimage.Attributes.Add("onclick", "javascript:window.open('" +
                    emailredirect + "');");
                mailloginimage.ToolTip = "Click here to open Windows Live E-mail";
                mailloginimage.Attributes.Add("onmouseover", "this.style.cursor='hand';");
                mailloginimage.Attributes.Add("onmouseout", "this.style.cursor='default';");
                skydriveloginimage.Attributes.Add("onclick", "javascript:window.open('" +
                    skydriveredirect + "');");
                skydriveloginimage.ToolTip = "Click here to open Windows Live SkyDrive";
                skydriveloginimage.Attributes.Add("onmouseover", "this.style.cursor='hand';");
                skydriveloginimage.Attributes.Add("onmouseout", "this.style.cursor='default';");
                calendarloginimage.Attributes.Add("onclick", "javascript:window.open('" +
                    calendarredirect + "');");
                calendarloginimage.ToolTip = "Click here to open Windows Live Calendar";
                calendarloginimage.Attributes.Add("onmouseover", "this.style.cursor='hand';");
                calendarloginimage.Attributes.Add("onmouseout", "this.style.cursor='default';");
                photologinimage.Attributes.Add("onclick", "javascript:window.open('" +
                    photoredirect + "');");
                photologinimage.ToolTip = "Click here to open Windows Live Photos";
                photologinimage.Attributes.Add("onmouseover", "this.style.cursor='hand';");
                photologinimage.Attributes.Add("onmouseout", "this.style.cursor='default';");       

                // Now we need to add the controls to the layout
                mainbuttoncell.Controls.Add(mainloginimage);
                mailbuttoncell.Controls.Add(mailloginimage);
                skydrivebuttoncell.Controls.Add(skydriveloginimage);
                calendarbuttoncell.Controls.Add(calendarloginimage);
                photobuttoncell.Controls.Add(photologinimage);
                liveidcell.Controls.Add(liveid);
                mainbuttonrow.Cells.Add(mainbuttoncell);
                subbuttonrow.Cells.Add(mailbuttoncell);
                subbuttonrow.Cells.Add(skydrivebuttoncell);
                subbuttonrow.Cells.Add(calendarbuttoncell);
                subbuttonrow.Cells.Add(photobuttoncell);
                liveidrow.Cells.Add(liveidcell);
                livelogon.Rows.Add(mainbuttonrow);
                livelogon.Rows.Add(subbuttonrow);
                livelogon.Rows.Add(liveidrow);

                // Finally add the table to the content panel, as well as the wrapping DIV tags
                Literal startdiv = new Literal();
                startdiv.Text = "<div style=\"border:2px solid #ccc; padding:5px; margin-bottom:5px; \">";
                // width: 150px; height: 50px; overflow: auto;
                Literal enddiv = new Literal();
                enddiv.Text = "</div>";
                this.Controls.Add(startdiv);
                this.Controls.Add(livelogon);
                this.Controls.Add(enddiv);
            }
            catch
            {
                // An error occurred so don't create/display the web part
            }
        }

        #endregion

        #region Support Functions

        /// <summary>
        /// This checks the application configuration to see if any global settings have been specified
        /// </summary>
        private void LoadGlobalSettings()
        {
            if (ConfigurationManager.AppSettings.AllKeys.Contains("SSOServer"))
                _ssoserver = ConfigurationManager.AppSettings["SSOServer"];
            if (ConfigurationManager.AppSettings.AllKeys.Contains("SSOServerPort"))
            {
                int ssoserverport = 11000;
                int.TryParse(ConfigurationManager.AppSettings["SSOServerPort"], out ssoserverport);
                _ssoserverport = ssoserverport;
            }
            if (ConfigurationManager.AppSettings.AllKeys.Contains("SSOServerUser"))
                _ssoserveruser = ConfigurationManager.AppSettings["SSOServerUser"];
            if (ConfigurationManager.AppSettings.AllKeys.Contains("SSOServerPassword"))
                _ssoserveruserpassword = ConfigurationManager.AppSettings["SSOServerPassword"];

            if (ConfigurationManager.AppSettings.AllKeys.Contains("SiteID"))
            {
                int siteid = 0;
                int.TryParse(ConfigurationManager.AppSettings["SiteID"], out siteid);
                _siteid = siteid;
            }
            if (ConfigurationManager.AppSettings.AllKeys.Contains("ProxyServer"))
                _proxyserver = ConfigurationManager.AppSettings["ProxyServer"];
            if (ConfigurationManager.AppSettings.AllKeys.Contains("LoginTimeout"))
            {
                int logintimeout = 1;
                int.TryParse(ConfigurationManager.AppSettings["LoginTimeout"], out logintimeout);
                _logintimeout = logintimeout;
            }
            if (ConfigurationManager.AppSettings.AllKeys.Contains("CertificateFile"))
                _certificatefile = ConfigurationManager.AppSettings["CertificateFile"];
            if (ConfigurationManager.AppSettings.AllKeys.Contains("CertificatePassword"))
                _certificatepassword = ConfigurationManager.AppSettings["CertificatePassword"];
            if (ConfigurationManager.AppSettings.AllKeys.Contains("CertificateThumbprint"))
                _certificatethumbprint = ConfigurationManager.AppSettings["CertificateThumbprint"];

            if (ConfigurationManager.AppSettings.AllKeys.Contains("AccountStore"))
            {
                if (Enum.GetNames(typeof(AccountStoreTypes)).Contains(ConfigurationManager.AppSettings["AccountStore"]))
                {
                    _accountstore = (AccountStoreTypes)Enum.Parse(typeof(AccountStoreTypes),
                    ConfigurationManager.AppSettings["AccountStore"]);
                }
            }
            if (ConfigurationManager.AppSettings.AllKeys.Contains("ActiveDirectoryDomain"))
                _activedirectorydomain = ConfigurationManager.AppSettings["ActiveDirectoryDomain"];
            if (ConfigurationManager.AppSettings.AllKeys.Contains("ActiveDirectoryProperty"))
                _activedirectoryproperty = ConfigurationManager.AppSettings["ActiveDirectoryProperty"];
            if (ConfigurationManager.AppSettings.AllKeys.Contains("ActiveDirectoryUser"))
                _activedirectoryuser = ConfigurationManager.AppSettings["ActiveDirectoryUser"];
            if (ConfigurationManager.AppSettings.AllKeys.Contains("ActiveDirectoryPassword"))
                _activedirectorypassword = ConfigurationManager.AppSettings["ActiveDirectoryPassword"];

            if (ConfigurationManager.AppSettings.AllKeys.Contains("AccessType"))
            {
                if (Enum.GetNames(typeof(SSOAuthenticationMethods)).Contains(ConfigurationManager.AppSettings["AccessType"]))
                {
                    _accesstype = (SSOAuthenticationMethods)Enum.Parse(typeof(SSOAuthenticationMethods),
                    ConfigurationManager.AppSettings["AccessType"]);
                }
            }
            if (ConfigurationManager.AppSettings.AllKeys.Contains("LiveEDUDomain"))
                _liveedudomain = ConfigurationManager.AppSettings["LiveEDUDomain"];

            if (ConfigurationManager.AppSettings.AllKeys.Contains("LiveEDUImageURL"))
                _liveeduimageurl = ConfigurationManager.AppSettings["LiveEDUImageURL"];

            if (ConfigurationManager.AppSettings.AllKeys.Contains("DisplayMailLogin"))
            {
                bool displaymaillogin = true;
                bool.TryParse(ConfigurationManager.AppSettings["DisplayMailLogin"], out displaymaillogin);
                _displaymaillogin = displaymaillogin;
            }
            if (ConfigurationManager.AppSettings.AllKeys.Contains("MailImageURL"))
                _mailimageurl = ConfigurationManager.AppSettings["MailImageURL"];

            if (ConfigurationManager.AppSettings.AllKeys.Contains("DisplaySkyDriveLogin"))
            {
                bool displayskydrivelogin = true;
                bool.TryParse(ConfigurationManager.AppSettings["DisplaySkyDriveLogin"], out displayskydrivelogin);
                _displayskydrivelogin = displayskydrivelogin;
            }
            if (ConfigurationManager.AppSettings.AllKeys.Contains("SkyDriveImageURL"))
                _skydriveimageurl = ConfigurationManager.AppSettings["SkyDriveImageURL"];

            if (ConfigurationManager.AppSettings.AllKeys.Contains("DisplayCalendarLogin"))
            {
                bool displaycalendarlogin = true;
                bool.TryParse(ConfigurationManager.AppSettings["DisplayCalendarLogin"], out displaycalendarlogin);
                _displaycalendarlogin = displaycalendarlogin;
            }
            if (ConfigurationManager.AppSettings.AllKeys.Contains("CalendarImageURL"))
                _calendarimageurl = ConfigurationManager.AppSettings["CalendarImageURL"];

            if (ConfigurationManager.AppSettings.AllKeys.Contains("DisplayPhotoLogin"))
            {
                bool displayphotologin = true;
                bool.TryParse(ConfigurationManager.AppSettings["DisplayPhotoLogin"], out displayphotologin);
                _displayphotologin = displayphotologin;
            }
            if (ConfigurationManager.AppSettings.AllKeys.Contains("PhotoImageURL"))
                _photoimageurl = ConfigurationManager.AppSettings["PhotoImageURL"];
        }

        /// <summary>
        /// Gets the users Windows Live Login ID
        /// </summary>
        /// <returns>The Windows Live Login ID for the user</returns>
        private string GetLiveAccount()
        {
            // First grabbed the logged in user details
            bool usesharepoint = true;
            string username = String.Empty;
            
            // Attempt to read the current SharePoint context, and if that fails, use 
            // standard HTTP
            try
            {
                username = SPContext.Current.Web.CurrentUser.LoginName;
            }
            catch
            {
                // We cannot read the SP context so use the standard HTTP
                usesharepoint = false;
                username = HttpContext.Current.User.Identity.Name;
            }                

            if (usesharepoint == true && _accountstore == AccountStoreTypes.SharePointEmail)
            {
                // As we have a SharePoint context and the account store is set to use SharePoint,
                // attempt to grab the e-mail property of the current user
                SharePointEmailSecurity sharepoint = new SharePointEmailSecurity();
                return sharepoint.GetWindowsLiveID(SPContext.Current, String.Empty, _liveedudomain);
            }
            else
            {
                // Either we are using active directory explicitly or the SharePoint context isn't 
                // available, so attempt to use AD lookups
                
                ActiveDirectoryEmailSecurity ad = new ActiveDirectoryEmailSecurity();
                if (_activedirectoryuser == String.Empty || _activedirectorypassword == String.Empty)
                    return ad.GetWindowsLiveID(username,
                        "DOMAIN=" + _activedirectorydomain + ";PROPERTY=" + _activedirectoryproperty,
                        _liveedudomain);
                else
                    return ad.GetWindowsLiveID(username,
                        "DOMAIN=" + _activedirectorydomain + ";PROPERTY=" + _activedirectoryproperty +
                        ";USER=" + _activedirectoryuser + ";PASSWORD=" + _activedirectorypassword,
                        _liveedudomain);
            }
        }

        /// <summary>
        /// This returns a configured and open client based on the web part properties to use for
        /// accessing the Single Sign On
        /// </summary>
        /// <returns>A prepared SSO Client</returns>
        private SSOClient.SSOClient GetClient()
        {
            // Determine the type of connection
            if (_accesstype == SSOAuthenticationMethods.Direct)
            {
                // As we are accessing directly, pass all configured properties through to the constructor
                // and return an SSO client for direct, depending on where the certificate is stored
                if (_certificatefile == null || _certificatefile == String.Empty)
                {
                    // As no certificate file was specified, assume we are using a certificate stored
                    // in the cert store
                    return new SSOClient.SSOClient(_siteid, _proxyserver, _logintimeout,
                        _certificatethumbprint);
                }
                else
                {
                    // As a certificate file was specified, use that
                    return new SSOClient.SSOClient(_siteid, _proxyserver, _logintimeout,
                        _certificatefile, _certificatepassword);
                }
            }
            else
            {
                // As we are accessing through the middle tier, return a new middle tier client
                // connection
                return new SSOClient.SSOClient(_ssoserver, _ssoserverport, _ssoserveruser,
                    _ssoserveruserpassword);
            }
        }

        #endregion
    }
}
